//
//  CXDNetHelp.m
//  Package
//
//  Created by 陈雪丹 on 2018/4/27.
//  Copyright © 2018年 cxd. All rights reserved.
//

#import "CXDNetHelp.h"
#import <AFNetworking/AFNetworking.h>

static AFHTTPSessionManager *_shareManager = nil;

@implementation CXDNetHelp

+ (AFHTTPSessionManager *)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _shareManager = [AFHTTPSessionManager manager];
        _shareManager.requestSerializer = [AFJSONRequestSerializer serializer];
        _shareManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        _shareManager.requestSerializer.timeoutInterval = 30.f;
        _shareManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml", @"text/plain",@"image/png", nil];
    });
    return _shareManager;
}

+ (void)getRequestWithURLString:(NSString * _Nullable)urlString parameters:(nullable id)parameters success:(_Nullable successBlock)success failure:(nullable failureBlock)failure {
    AFHTTPSessionManager *manager = [self shareManager];
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    [manager GET:urlString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSString *tempString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSObject *dict = [NSJSONSerialization JSONObjectWithData:[tempString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        if (success) {
            if (dict) {
                success(dict);
            }else {
                success(tempString);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (failure) {
            failure(error);
        }
        [self handleErrorTask:task error:error];
    }];
}

+ (void)getQRImageDataWithURLString:(NSString * _Nullable)urlString parameters:(nullable id)parameters success:(_Nullable successBlock)success failure:(nullable failureBlock)failure {
    AFHTTPSessionManager *manager = [self shareManager];
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    [manager GET:urlString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSString *tempString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSObject *dict = [NSJSONSerialization JSONObjectWithData:[tempString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",tempString);
        if (success) {
            success(dict);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (failure) {
            failure(error);
        }
        [self handleErrorTask:task error:error];
    }];
}


+ (void)postRequestWithURLString:(NSString * _Nullable)urlString parameters:(nullable id)parameters success:(_Nullable successBlock)success failure:(nullable failureBlock)failure {
    AFHTTPSessionManager *manager = [self shareManager];
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    });
    [manager POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSString *tempString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSObject *dict = [NSJSONSerialization JSONObjectWithData:[tempString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        if (success) {
            success(dict);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (failure) {
            failure(error);
        }
        [self handleErrorTask:task error:error];
    }];
}

//错误数据处理
+ (void)handleErrorTask:(NSURLSessionDataTask *)task error:(NSError *)error {
    if (error.code == -1009) {//网络不可用
        [CXDNoticeView showNoticeViewWithString:@"当前网络不可用，请检查网络设置"];
    }else {
        if ([error.localizedDescription isEqualToString:@"未能读取数据，因为它的格式不正确。"] || error.code == 3840 || error.code == -1004) {
            [CXDNoticeView showNoticeViewWithString:@"服务器错误"];
        }else {
            /*注意:这里要强转下*/
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            if (responses.statusCode == 401 || responses.statusCode == 500) {
                [CXDNoticeView showNoticeViewWithString:@"账户异常，请重新登录"];
            }else if (responses.statusCode == 400 || responses.statusCode == 415 || responses.statusCode == 404) {
                [CXDNoticeView showNoticeViewWithString:@"网络异常，请稍后重试"];
            }else {
                NSLog(@"%@",error.localizedDescription);
                [CXDNoticeView showNoticeViewWithString:error.localizedDescription];
            }
        }
    }
}

+ (AFHTTPSessionManager *)sessionManagerAddHeader {
    AFHTTPSessionManager *manager = [self shareManager];
    AFHTTPRequestSerializer *requestSerialize = [AFJSONRequestSerializer serializer];
//    if ([CXDHelper token] != nil) {
//        [requestSerialize setValue:[CXDHelper token] forHTTPHeaderField:ZXCConstTokenKey];
//        [requestSerialize setValue:[CXDHelper uuidForDevice] forHTTPHeaderField:ZXCDeviceIDKey];
//        [requestSerialize setValue:ZXCIOS forHTTPHeaderField:ZXCAPPTypeKey];
//    }
    manager.requestSerializer = requestSerialize;
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    return manager;
}


@end
